<?php

class BackendController extends Module
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly', // we only allow deletion via POST request
            'ajaxOnly + main',
		);
	}
    public function init()
    {

    }
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','addnewmenuitem','articles','ajax_modal','ajax_article_grid',
                                 'ajax_category_grid','menuitems','refresh','menuItemDetails','changeStatus',
                                 'ajaxitemdelete','ajaxitempublish','ajaxitemunpublish','setmainpage'),
				'roles'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        if(Yii::app()->request->isAjaxRequest)
        {
            $model = MenuItem::model()->findByPk($id);

            $this->renderPartial('view',array(
                'model'=>$model,
            ),false,true);
            Yii::app()->end();

        }
        else
        {
            $this->render('view',array(
                'model'=>MenuItem::model()->findByPk($id),
            ));
        }
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new MenuItem;

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['MenuItem']))
		{
			$model->attributes=$_POST['MenuItem'];

            if($model->save())
            {
                Yii::app()->user->setFlash('success',Yii::t('MenuModule.base','The menu item was successfully created.'));
                $this->redirect(Yii::app()->createUrl('/menu/backend/menuitems'));
            }
		}
		$this->render('createitem',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
        $model = MenuItem::model()->findByPk($id);
        $this->performAjaxValidation($model);
        if(isset($_POST['MenuItem']))
        {
            $model->attributes = $_POST['MenuItem'];

            if($model->save())
            {
                Yii::app()->user->setFlash('success',Yii::t('MenuModule.base','Menu item was successfully updated.'));
                $this->redirect(Yii::app()->createUrl('/menu/backend/menuitems'));
            }
        }
        if(Yii::app()->request->isAjaxRequest)
        {
            $this->renderPartial('_item',array('model'=>$model),false,true);
            Yii::app()->end();
        }
		$this->render('updateitem',array(
			'model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Menu');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Menu('search');

		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Menu']))
			$model->attributes=$_GET['Menu'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Menu the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Menu::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

    /**
	 * Performs the AJAX validation.
	 * @param Menu $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='menu-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

    //
    public function actionArticles()
    {
        $model = new Article('search');

        if(Yii::app()->request->isAjaxRequest){

            $this->renderPartial('articles',array('model'=>$model));
            // Завершаем приложение
            Yii::app()->end();
        }
    }

    //
    public function actionAjax_Modal()
    {
        if(Yii::app()->request->isAjaxRequest)
        {
            $this->renderPartial('ajax_modal');
            Yii::app()->end();
        }
    }

    //Генерируем Grid статей
    public function actionAjax_Article_Grid()
    {
        $model = new Article('search');
        $model->unsetAttributes();

        if(isset($_GET['Article'])) // чтобы работали функции поиска нужно передать параметры в модель
                $model->attributes=$_GET['Article'];

        $this->renderPartial('ajax_article_grid',array('model'=>$model),false,true);
        Yii::app()->end();
    }

    //Генерируем Grid категории
    public function actionAjax_Category_Grid()
    {
        $model = new Category();
        $model->unsetAttributes();
        if(isset($_GET['Category'])) // чтобы работали функции поиска нужно передать параметры в модель
            $model->attributes=$_GET['Category'];

        $this->renderPartial('ajax_category_grid',array('model'=>$model),false,true);
        Yii::app()->end();
    }

    //Выводим список дочерних элементов меню
    public function actionMenuItems()
    {
        $model = new MenuItem('search');
        $model->unsetAttributes();
        if(isset($_GET['MenuItem']))
        {
            $model->attributes=$_GET['MenuItem'];
        }
        $this->render('menu_items',array('model'=>$model));
    }

    //Обновляет грид
    public function actionRefresh()
    {
        Yii::app()->clientscript->scriptMap['jquery.min.js'] = false;
        Yii::app()->clientscript->scriptMap['jquery.yiiactiveform.js'] = false;
        Yii::app()->clientscript->scriptMap['bootstrap.min.js'] = false;
        Yii::app()->clientscript->scriptMap['all.js'] = false;
        $model=new MenuItem;
        $this->renderPartial('_item',array(
            'model'=>$model,
        ),false,true);
    }

    public function actionChangeStatus()
    {
        $id = $_GET['id'];
        $status = 0;
        $sql = "UPDATE {{menu_item}} SET status= ABS(status - 1) WHERE id=:id ";
        $db = Yii::app()->db;
        $comm = $db->createCommand($sql);
        $comm->bindParam(':id',$id,PDO::PARAM_INT);
        $comm->query();
        echo $id;
    }


    //Предотвращяем повторную загрузку js библиотек про AJAX запросе
    protected function beforeAction($action) {
        if( Yii::app()->request->isAjaxRequest ) {
            Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
            Yii::app()->clientscript->scriptMap['jquery.js'] = false;
           // Yii::app()->clientscript->scriptMap[''] = false;
            //Yii::app()->clientScript->scriptMap['jquery-2.0.0.js'] = false;
            //Yii::app()->clientScript->scriptMap['jquery.ba-bbq.min.js'] = false;
        }

        return parent::beforeAction($action);
    }

    //
    public function actionAjaxItemDelete()
    {
        $items = $_GET['items'];
        if(count($items))
        {
            $q = Yii::app()->db->createCommand();
            foreach($items as $item)
            {
                $q->delete('{{menu_item}}','id=:item',array(':item'=>$item));
            }
            return true;
        }
    }

    //
    public function actionAjaxItemPublish()
    {
        $ids = $_GET['items'];
        $comm = Yii::app()->db->createCommand();
            foreach($ids as $id)
            {
                $comm->update('{{menu_item}}', array(
                    'status'=>1,
                ), 'id=:id', array(':id'=>$id));
            }
        return true;
    }

    //
    public function actionAjaxItemUnpublish()
    {
        $ids = $_GET['items'];
        $comm = Yii::app()->db->createCommand();
        foreach($ids as $id)
        {
            $comm->update('{{menu_item}}', array(
                'status'=>0,
            ), 'id=:id', array(':id'=>$id));
        }
        return true;
    }

    //Устанавливаем главную страницу
    public function actionSetMainPage($id)
    {
       if(isset($id) && is_numeric($id))
       {
           $connection = Yii::app()->db;
           $transaction=$connection->beginTransaction();
           try
           {
               $posFirst = 1;

               $sql = "SELECT position FROM {{menu_item}} WHERE id=:id";
               $result = $connection->createCommand($sql)->bindParam(':id',$id,PDO::PARAM_STR)->queryRow();

               $sql = "UPDATE {{menu_item}} SET position=:newPos WHERE position=:posFirst";
               $connection->createCommand($sql)->bindParam(':newPos',$result['position'],PDO::PARAM_INT)->bindParam(':posFirst',$posFirst,PDO::PARAM_INT)->execute();

               $sql = "UPDATE {{menu_item}} SET position=:pos WHERE id=:id";
               $connection->createCommand($sql)->bindParam(':pos',$posFirst,PDO::PARAM_INT)->bindParam(':id',$id,PDO::PARAM_INT)->execute();

               $transaction->commit();
               return true;
           }
           catch(Exception $e) // в случае возникновения ошибки при выполнении одного из запросов выбрасывается исключение
           {
               $transaction->rollback();
               echo $e->getMessage();
           }
           return true;
       }
    }
}
